from PyQt5.QtCore import QThread, pyqtSignal
import cv2
from typing import List

from interfaces.detector_interface import IDetector
from models.data_models import ImageInfo, DetectionResult

class DetectionWorker(QThread):
    """异步检测工作线程"""
    
    # 信号定义
    detection_finished = pyqtSignal(int, DetectionResult)  # 单张检测完成
    batch_progress = pyqtSignal(int, int)  # 批量处理进度 (current, total)
    batch_finished = pyqtSignal()  # 批量处理完成
    error_occurred = pyqtSignal(str)  # 错误信号
    
    def __init__(self, detector: IDetector):
        super().__init__()
        self.detector = detector
        self.image_list: List[ImageInfo] = []
        self.indices_to_process: List[int] = []
        self.should_stop = False
    
    def set_batch_task(self, image_list: List[ImageInfo], indices: List[int] = None):
        """设置批量处理任务"""
        self.image_list = image_list
        if indices is None:
            self.indices_to_process = list(range(len(image_list)))
        else:
            self.indices_to_process = indices
    
    def run(self):
        """执行检测任务"""
        try:
            total = len(self.indices_to_process)
            
            for i, index in enumerate(self.indices_to_process):
                if self.should_stop:
                    break
                
                image_info = self.image_list[index]
                
                # 加载图像
                image = cv2.imread(image_info.path)
                if image is None:
                    self.error_occurred.emit(f"无法加载图像: {image_info.filename}")
                    continue
                
                # 转换为RGB
                image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
                
                # 执行检测
                result = self.detector.detect(image_rgb, image_info.path)
                
                # 更新图像信息
                image_info.is_processed = True
                image_info.detection_result = result
                
                # 发送信号
                self.detection_finished.emit(index, result)
                self.batch_progress.emit(i + 1, total)
            
            self.batch_finished.emit()
            
        except Exception as e:
            self.error_occurred.emit(f"检测过程中发生错误: {e}")
    
    def stop(self):
        """停止处理"""
        self.should_stop = True
